package main_app

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/driver/desktop"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
	"github.com/MzoroHaHa/dev-tools/backend/app/browser"
	"github.com/MzoroHaHa/dev-tools/backend/app/info"
	"github.com/MzoroHaHa/dev-tools/backend/app/main-app/functions"
	"github.com/MzoroHaHa/dev-tools/backend/app/resources"
	"image/color"
	"strings"
)

var mainApp fyne.App
var mainWindow fyne.Window

var contentLine = make([]string, 0)

type appIcon struct {
}

func (a *appIcon) Name() string {
	return "app icon"
}
func (a *appIcon) Content() []byte {
	return resources.AppIcon
}

func init() {
	mainApp = app.New()
	//app.NewWithID("com.zoro.dt.preferences")
	mainApp.SetIcon(&appIcon{})
	mainApp.Settings().SetTheme(defaultDtTheme)
	mainWindow = mainApp.NewWindow("dev-tools")
	functions.SetMainApp(mainApp)

	contentLine = append(contentLine, "Starting")
	mainLabel := widget.NewLabel("Welcome to dev-tools!")
	mainWindow.SetContent(mainLabel)
	mainWindow.CenterOnScreen()
	// 点击关闭时，程序不退出，隐藏主窗口
	mainWindow.SetCloseIntercept(func() {
		mainWindow.Hide()
	})

	if desk, ok := mainApp.(desktop.App); ok {
		m := fyne.NewMenu("DT",
			fyne.NewMenuItem("Panel", func() {
				mainWindow.Resize(fyne.NewSize(800, 600))
				reloadRunningStatus()
				mainWindow.Show()
			}),
			fyne.NewMenuItem("App", func() {
				browser.RunChrome()
			}),
			fyne.NewMenuItem("Close", func() {
				browser.CloseChrome()
			}),
		)
		desk.SetSystemTrayMenu(m)
		desk.SetSystemTrayIcon(&appIcon{})

	}
}

func Run() {
	mainApp.Run()
}

func reloadRunningStatus() {
	runningInfo := info.RunningInfo()
	format := "%-20s: %s"

	textArr := []fyne.CanvasObject{
		canvas.NewText(fmt.Sprintf(format, info.GoVersionKey, runningInfo[info.GoVersionKey]), color.Black),
		canvas.NewText(fmt.Sprintf(format, info.GoOSKey, runningInfo[info.GoOSKey]), color.Black),
		canvas.NewText(fmt.Sprintf(format, info.GoArchKey, runningInfo[info.GoArchKey]), color.Black),
		canvas.NewText(fmt.Sprintf(format, info.VersionKey, runningInfo[info.VersionKey]), color.Black),
		canvas.NewText(fmt.Sprintf(format, info.ServerKey, runningInfo[info.ServerKey]), color.Black),
		canvas.NewText(fmt.Sprintf(format, info.ChromePageUrlKey, runningInfo[info.ChromePageUrlKey]), color.Black),
		canvas.NewText(fmt.Sprintf(format, info.ChromeErrKey, runningInfo[info.ChromeErrKey]), color.Black),
	}
	args := runningInfo[info.ChromeArgsKey] // 太长了，不方便看
	if len(args) > 0 {
		argArr := strings.Split(args, " ")
		for i, arg := range argArr {
			_format := "%-21s %s"
			label := " "
			if i == 0 {
				label = info.ChromeArgsKey
				_format = format
			}
			textArr = append(textArr, canvas.NewText(fmt.Sprintf(_format, label, arg), color.Black))
		}
	}
	c := container.New(layout.NewVBoxLayout(), textArr...)

	scroll := container.NewScroll(c) // 横向纵向都可以滚动
	mainWindow.SetContent(scroll)
	mainWindow.Resize(fyne.NewSize(800, 600))
}
